﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Sector7.Medical.EntityType;
using Sector7.Framework.Core;
using Sector7.Framework.Enums;
using Sector7.Framework.Utility;
using Sector7.Medical.Biz;
using Sector7.Medical.Consts;
using System.Reflection;
using Sector7.Medical.Utility;
using Sector7.Framework.EntityType;
using Sector7.Medical.Enums;

namespace Sector7.Medical.BIZM.Controls
{
    /// <summary>
    /// OutpatientRegistryControl.xaml 的交互逻辑
    /// </summary>
    public partial class OutpatientRegistryControl : AddModeControlBase
    {
        #region Accessor

        /// <summary>
        /// 挂号信息
        /// </summary>
        private M7_RegistryRecord RegistryRecord
        {
            get { return m_entity as M7_RegistryRecord; }
            set { m_entity = value; }
        }
        #endregion

        #region Public functions
        #endregion

        #region Private functions

        /// <summary>
        /// Key Down
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OutpatientRegistryControl_KeyDown(object sender, KeyEventArgs e)
        {
            switch (e.Key)
            {
                case Key.F9:
                    SetCurrentOperationType(OPERATION_REGISTRY);
                    break;
                case Key.F10:
                    SetCurrentOperationType(OPERATION_CHANGE_REGISTRY);
                    break;
                case Key.F11:
                    SetCurrentOperationType(OPERATION_BESPOKE_REGISTRY);
                    break;
                case Key.F12:
                    SetCurrentOperationType(OPERATION_NEW_CARD);
                    break;
                case Key.F5:
                    SetCurrentCardType(TYPE_SOCIAL_SECURITY_CARD);
                    break;
                case Key.F6:
                    SetCurrentCardType(TYPE_MEDICAL_HISTORY_CARD);
                    break;
                case Key.F7:
                    SetCurrentCardType(TYPE_IDENTIFICATION_CARD);
                    break;
                case Key.F8:
                    SetCurrentCardType(TYPE_MEDICAL_CARD);
                    break;
                case Key.Enter:
                    if (e.OriginalSource is TextBox && (e.OriginalSource as TextBox).Tag != null && (e.OriginalSource as TextBox).Tag.ToString() == "VisitNo")
                    {
                        GetCitizenByRegistrationNumber();
                    }
                    else
                    {
                        UIInputDone();
                    }
                    break;
            }
        }

        /// <summary>
        /// Form Load
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OutpatientRegistryControl_Loaded(object sender, RoutedEventArgs e)
        {
            m_crud = CrudType.Unknown;

            SetCurrentOperationType(OPERATION_NEW_CARD);

            Senvironments.ProgressWindow.Visibility = Visibility.Visible;

            var worker = BackgroundWorkerUtil.GetWorker(this);
            worker.DoWork += new System.ComponentModel.DoWorkEventHandler(LoadData_DoWork);
            worker.RunWorkerAsync();
        }

        /// <summary>
        /// 加载数据工作线程
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void LoadData_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            GetData();

            this.Dispatcher.BeginInvoke(new DelegateWithNothing(LoadData));
        }

        /// <summary>
        /// 获取数据
        /// </summary>
        private new void GetData()
        {
            m_divisionId = "999999";

            M7_ChargeItem newCardChargeItem = Agent_INFS.GetChargeItem(C_FixedChargeId.NEW_CARD);
            if (newCardChargeItem != null)
            {
                m_newCardFee = newCardChargeItem.Price;
            }

            m_registryFeeList = Agent_INFS.GetRegistryFeeList();

            m_outpatientTypeList = new List<M7_OutpatientType>();
            FieldInfo[] oFieldArr = typeof(C_OutpatientType).GetFields();
            foreach (FieldInfo field in oFieldArr)
            {
                object[] attributeArrary = field.GetCustomAttributes(typeof(ConstAttribute), true);
                if (attributeArrary.Length == 1)
                {
                    ConstAttribute attribute = attributeArrary[0] as ConstAttribute;
                    string displayText = attribute.DisplayText;
                    if (!string.IsNullOrEmpty(displayText))
                    {
                        object value = field.GetValue(null);
                        if (value is int)
                        {
                            m_outpatientTypeList.Add(new M7_OutpatientType(Convert.ToInt32(value), displayText));
                        }
                    }
                }
            }
            //m_outpatientTypeList.Add(new M7_OutpatientType(C_OutpatientType.FirstVisit, "初诊"));
            //m_outpatientTypeList.Add(new M7_OutpatientType(C_OutpatientType.FirstVisit, "复诊"));

            m_registryTypeList = new List<M7_RegistryType>();
            FieldInfo[] rFieldArr = typeof(C_RegistryType).GetFields();
            foreach (FieldInfo field in rFieldArr)
            {
                object[] attributeArrary = field.GetCustomAttributes(typeof(ConstAttribute), true);
                if (attributeArrary.Length == 1)
                {
                    ConstAttribute attribute = attributeArrary[0] as ConstAttribute;
                    string displayText = attribute.DisplayText;
                    if (!string.IsNullOrEmpty(displayText))
                    {
                        object value = field.GetValue(null);
                        if (value is int)
                        {
                            m_registryTypeList.Add(new M7_RegistryType(Convert.ToInt32(value), displayText));
                        }
                    }
                }
            }
            //m_registryTypeList.Add(new M7_RegistryType(C_RegistryType.NormalRegistry, "普通挂号"));
            //m_registryTypeList.Add(new M7_RegistryType(C_RegistryType.SpecialistRegistry, "专家挂号"));
            //m_registryTypeList.Add(new M7_RegistryType(C_RegistryType.EmergencyRegistry, "急诊挂号"));

            m_insuranceTypeTypeList = new List<M7_InsuranceType>();
            FieldInfo[] iFieldArr = typeof(C_InsuranceType).GetFields();
            foreach (FieldInfo field in iFieldArr)
            {
                object[] attributeArrary = field.GetCustomAttributes(typeof(ConstAttribute), true);
                if (attributeArrary.Length == 1)
                {
                    ConstAttribute attribute = attributeArrary[0] as ConstAttribute;
                    string displayText = attribute.DisplayText;
                    if (!string.IsNullOrEmpty(displayText))
                    {
                        object value = field.GetValue(null);
                        if (value is int)
                        {
                            m_insuranceTypeTypeList.Add(new M7_InsuranceType(Convert.ToInt32(value), displayText));
                        }
                    }
                }
            }
            //m_insuranceTypeTypeList.Add(new M7_InsuranceType(C_InsuranceType.None, "未参保"));
            //m_insuranceTypeTypeList.Add(new M7_InsuranceType(C_InsuranceType.MedicalInsurance, "医疗保险"));
            //m_insuranceTypeTypeList.Add(new M7_InsuranceType(C_InsuranceType.SocialSecurity, "社会保险"));
            //m_insuranceTypeTypeList.Add(new M7_InsuranceType(C_InsuranceType.CommerialInsurance, "商业保险"));

            m_genderList = Agent_INFS.GetGenderList();
            //m_deptList = Agent_INFS.GetDepartmentListByComflags(C_DepartmentFlags.DEPARTMENT | C_DepartmentFlags.CAN_REGISTRY);
            m_subDeptList = Agent_INFS.GetDepartmentListByComflags(C_DepartmentFlags.SUB_DEPARTMENT | C_DepartmentFlags.CAN_REGISTRY);
            m_empList = Agent_INFS.GetDoctorOrSpecialist();

            m_registryRecordList = Agent_BIZS.GetRegistryRecoredListInOneDay(DateTime.Now);

            for (int i = 0; i < m_registryRecordList.Count; i++)
            {
                M7_RegistryRecord registryRecord = m_registryRecordList[i];

                SetRegistryRecordOtherInfor(registryRecord);
            }
        }

        /// <summary>
        /// Show Visit No To UI
        /// </summary>
        private void ShowVisitNoToUI()
        { 
            int visitNo = Agent_SYSS.GetBinarySeed(C_M7_TableName.REGISTRY_RECORD, DateTime.Now.ToString("yyyyMMdd"));
            txbVisitNo.Text = visitNo.ToString();
        }

        /// <summary>
        /// 显示挂号信息列表到UI
        /// </summary>
        private void LoadRegistryRecordListOnUI()
        {
            ClientUtil.LoadItemsSource(dtgRegistryRecord, m_registryRecordList);

            int totalRegistryRecordCount = m_registryRecordList.Count;
            int normalRegistryRecordCount = 0;
            int specialistRegistryRecordCount = 0;
            int emergencyRegistryCount = 0;
            decimal totalAcount = 0;

            foreach (M7_RegistryRecord registryRecord in m_registryRecordList)
            {
                if (registryRecord.RegistryType == C_RegistryType.NormalRegistry)
                {
                    normalRegistryRecordCount++;
                }
                if (registryRecord.RegistryType == C_RegistryType.SpecialistRegistry)
                {
                    specialistRegistryRecordCount++;
                }
                if (registryRecord.RegistryType == C_RegistryType.EmergencyRegistry)
                {
                    emergencyRegistryCount++;
                }
                totalAcount += registryRecord.Amount;
            }

            sbiTotalRegistryRecordCount.Content = totalRegistryRecordCount.ToString();
            sbiNormalRegistryRecordCount.Content = normalRegistryRecordCount.ToString();
            sbiSpecialistRegistryRecordCount.Content = specialistRegistryRecordCount.ToString();
            sbiEmergencyRegistryCount.Content = emergencyRegistryCount.ToString();
            sbiTotalAmount.Content = totalAcount.ToString();
        }

        /// <summary>
        /// 设置M7_RegistryRecord的其它一些信息
        /// </summary>
        /// <param name="registryRecord"></param>
        private void SetRegistryRecordOtherInfor(M7_RegistryRecord registryRecord)
        {
            if (registryRecord.Patient != null)
            {
                M7_Gender gender = m_genderList.Find(delegate(M7_Gender __gender)
                {
                    return (__gender.GenderId == registryRecord.Patient.GenderId);
                });
                registryRecord.Patient.GenderStr = (gender != null ? gender.GenderName : "");

                registryRecord.Patient.AgeStr = CitizenUtil.CalculateAge(registryRecord.Patient.Birthday);

                registryRecord.OutpatientTypeObject = m_outpatientTypeList.Find(delegate(M7_OutpatientType __oType)
                {
                    return (__oType.OutpatientTypeId == registryRecord.OutpatientType);
                });

                registryRecord.RegistryTypeObject = m_registryTypeList.Find(delegate(M7_RegistryType __rType)
                {
                    return (__rType.RegistryTypeId == registryRecord.RegistryType);
                });

                registryRecord.InsuranceTypeObject = m_insuranceTypeTypeList.Find(delegate(M7_InsuranceType __iType)
                {
                    return (__iType.InsuranceTypeId == registryRecord.InsuranceType);
                });

                registryRecord.Department = m_subDeptList.Find(delegate(M7_Department __dept)
                {
                    return (__dept.DeptId == registryRecord.DeptId);
                });

                registryRecord.Doctor = m_empList.Find(delegate(M7_Employee __emp)
                {
                    return (__emp.EmpId == registryRecord.DoctorId);
                });

                registryRecord.Patient.BirthdayStr = registryRecord.Patient.Birthday.ToString("yyyy-MM-dd");
            }
        }

        /// <summary>
        /// 加载数据
        /// </summary>
        private void LoadData()
        {
            ClientUtil.LoadItemsSource(cbbOutpatientType, m_outpatientTypeList);
            ClientUtil.LoadItemsSource(cbbRegistryType, m_registryTypeList);
            ClientUtil.LoadItemsSource(cbbInsuranceType, m_insuranceTypeTypeList);
            ClientUtil.LoadItemsSource(cbbGender, m_genderList);
            ClientUtil.LoadItemsSource(cbbDept, m_subDeptList);
            LoadRegistryRecordListOnUI();

            txbCardFee.Text = m_newCardFee.ToString();

            Senvironments.ProgressWindow.Visibility = Visibility.Hidden;
        }

        /// <summary>
        /// Dept Combobox Selection Changed
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cbbDept_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cbbDept.SelectedValue != null)
            {
                List<M7_Employee> list = new List<M7_Employee>();
                int deptId = Convert.ToInt32(cbbDept.SelectedValue);
                foreach(M7_Employee emp in m_empList)
                {
                    if (emp.DeptId == deptId)
                    {
                        list.Add(emp);
                    }
                }
                ClientUtil.LoadItemsSource(cbbDoctor, list);
            }

            ShowRegistryFee();
        }

        /// <summary>
        /// OutpatientType Combobox Selection Changed
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cbbOutpatientType_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ShowRegistryFee();
        }

        /// <summary>
        /// RegistryType Combobox Selection Changed
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cbbRegistryType_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ShowRegistryFee();
        }

        /// <summary>
        /// Show Registry Fee
        /// </summary>
        private void ShowRegistryFee()
        {
            txbRegistryFee.Text = "";
            txbDiagnosticFee.Text = "";

            if (cbbDept.SelectedValue != null && cbbOutpatientType.SelectedValue != null && cbbRegistryType.SelectedValue != null)
            {
                M7_Department dept = m_subDeptList.Find(delegate(M7_Department __dept)
                {
                    return __dept.DeptId.ToString() == cbbDept.SelectedValue.ToString();
                });

                M7_RegistryFee registryFee = m_registryFeeList.Find(delegate(M7_RegistryFee __registryFee)
                {
                    return __registryFee.DeptId == dept.ParentId &&
                        __registryFee.OutpatientType.ToString() == cbbOutpatientType.SelectedValue.ToString() &&
                        __registryFee.RegistryType.ToString() == cbbRegistryType.SelectedValue.ToString();
                });

                if (registryFee != null)
                {
                    txbRegistryFee.Text = registryFee.RegistryFee.ToString();
                    txbDiagnosticFee.Text = registryFee.DiagnosticFee.ToString();

                    decimal totalFee = registryFee.RegistryFee + registryFee.DiagnosticFee;
                    if (m_currentOperation == OPERATION_NEW_CARD)
                    {
                        totalFee += m_newCardFee;
                    }
                    txbTotalAmount.Text = totalFee.ToString();
                }
                else
                {
                    txbTotalAmount.Text = "";
                    if (m_currentOperation == OPERATION_NEW_CARD)
                    {
                        txbTotalAmount.Text = m_newCardFee.ToString();
                    }
                }
            }
        }

        /// <summary>
        /// Patch Text Change
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txbFTAmount_TextChanged(object sender, TextChangedEventArgs e)
        {
            try
            {
                decimal totalFee = Convert.ToDecimal(txbTotalAmount.Text.Trim());
                decimal fatchFee = Convert.ToDecimal(txbFatchAmount.Text.Trim());

                txbBillAmount.Text = (fatchFee - totalFee).ToString(); ;
            }
            catch
            {
                txbBillAmount.Text = "";
            }
        }

        /// <summary>
        /// Date Select Changed
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dtpBirthday_SelectedDateChanged(object sender, SelectionChangedEventArgs e)
        {
            txbAge.Text = "";

            if (dtpBirthday.SelectedDate != null)
            {
                DateTime birthDay = (DateTime)dtpBirthday.SelectedDate;
                DateTime now = DateTime.Now;
                if (birthDay.CompareTo(now) > 0)
                {
                    Alert.ShowDialog(AlertType.Error, "出生日期大于当前时间");
                    return;
                }

                string ageStr = CitizenUtil.CalculateAge(birthDay);
                txbAge.Text = ageStr;
            }
        }

        /// <summary>
        /// Test Button Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnTest_Click(object sender, RoutedEventArgs e)
        {
            UIInputDone();
        }

        /// <summary>
        /// UI Input Down
        /// </summary>
        private void UIInputDone()
        {
            m_patient = null;
            m_registryRecord = null;
            m_registryCharge = null;
            m_newCardChange = null;

            if (CheckData())
            {
                AddData();
            }
            else
            {
                ShowErrors();
            }
        }

        /// <summary>
        /// 添加成功
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OutpatientRegistryControl_AddSuccess(object sender, EventArgs e)
        {
            Alert.ShowDialog(AlertType.Notification, "挂号成功");
            ClearDateOnUIForRegistrySucess();

            if (m_registryRecord != null)
            {
                m_registryRecordList.Insert(0, m_registryRecord);
                SetRegistryRecordOtherInfor(m_registryRecord);
                ShowVisitNoToUI();
            }
        }

        /// <summary>
        /// Check Data
        /// </summary>
        /// <returns></returns>
        protected override bool CheckData()
        {
            m_errors.Clear();

            string registrationNumber = txbRegistrationNumber.Text.Trim();
            string fullName = txbFullName.Text.Trim();
            string genderId = "";
            DateTime birthday = DateTime.Now;
            string outpatientTypeId = "";
            string registryTypeId = "";
            string insuranceTypeId = "";
            int deptId = -1;
            long doctorId = -1;
            decimal registryFee = 0;
            decimal diagnosticFee = 0;
            decimal newCardFee = 0;
            decimal totalFee = 0;
            decimal fatchFee = 0;
            string remark = txbRemark.Text.Trim();
            int visitNo = -1;

            try
            {
                visitNo = Convert.ToInt32(txbVisitNo.Text.Trim());
            }
            catch
            {
                m_errors.Add("就诊号", "为非法数字!");
            }
            if (m_currentOperation == OPERATION_NEW_CARD)
            {
                if (string.IsNullOrEmpty(registrationNumber))
                {
                    m_errors.Add("登记号", "不能为空!");
                }
            }
            if (string.IsNullOrEmpty(fullName))
            {
                m_errors.Add("姓名", "不能为空!");
            }
            if (cbbGender.SelectedValue == null)
            {
                m_errors.Add("性别", "不能为空!");
            }
            else
            {
                genderId = cbbGender.SelectedValue.ToString();
            }
            if (dtpBirthday.SelectedDate == null)
            {
                m_errors.Add("出生日期", "不能为空!");
            }
            else
            {
                birthday = (DateTime)dtpBirthday.SelectedDate;
            }
            if (cbbOutpatientType.SelectedValue == null)
            {
                m_errors.Add("门诊类型", "不能为空!");
            }
            else
            {
                outpatientTypeId = cbbOutpatientType.SelectedValue.ToString();
            }
            if (cbbRegistryType.SelectedValue == null)
            {
                m_errors.Add("挂号类型", "不能为空!");
            }
            else
            {
                registryTypeId = cbbRegistryType.SelectedValue.ToString();
            }
            if (cbbInsuranceType.SelectedValue == null)
            {
                m_errors.Add("医保类型", "不能为空!");
            }
            else
            {
                insuranceTypeId = cbbInsuranceType.SelectedValue.ToString();
            }
            if (cbbDept.SelectedValue == null)
            {
                m_errors.Add("科室", "不能为空!");
            }
            else
            {
                deptId = Convert.ToInt32(cbbDept.SelectedValue);
            }
            if (cbbDoctor.SelectedValue == null)
            {
                m_errors.Add("医生", "不能为空!");
            }
            else
            {
                doctorId = Convert.ToInt64(cbbDoctor.SelectedValue);
            }
            try
            {
                registryFee = Convert.ToDecimal(txbRegistryFee.Text.Trim());
                if (registryFee == 0)
                {
                    m_errors.Add("挂号费", "无挂号费!");
                }
            }
            catch
            {
                m_errors.Add("挂号费", "为非法数字!");
            }
            try
            {
                diagnosticFee = Convert.ToDecimal(txbDiagnosticFee.Text.Trim());
                if (diagnosticFee == 0)
                {
                    m_errors.Add("诊察费", "无诊察费!");
                }
            }
            catch
            {
                m_errors.Add("诊察费", "为非法数字!");
            }
            try
            {
                totalFee = Convert.ToDecimal(txbTotalAmount.Text.Trim());
            }
            catch
            {
                m_errors.Add("总计", "为非法数字!");
            }
            try
            {
                fatchFee = Convert.ToDecimal(txbFatchAmount.Text.Trim());
            }
            catch
            {
                m_errors.Add("收取", "为非法数字!");
            }
            if(m_currentOperation == OPERATION_NEW_CARD)
            {
                try
                {
                    newCardFee = Convert.ToDecimal(txbCardFee.Text.Trim());
                    if (newCardFee == 0)
                    {
                        m_errors.Add("开卡费", "无开卡费!");
                    }
                }
                catch
                {
                    m_errors.Add("收取", "为非法数字!");
                }
            }

            if (m_errors.Count == 0)
            {
                if (fatchFee < totalFee)
                {
                    m_errors.Add("收取", "费用不足!");
                }
            }

            if (m_errors.Count == 0)
            {
                DateTime nowDT = DateTime.Now;
                string citizenId = "";

                if (m_currentOperation == OPERATION_NEW_CARD)
                {
                    m_patient = new M7_Patient();
                    m_citizen = new S7_Citizen();
                    m_newCardChange = new M7_ChargeRecord();
                    citizenId = Guid.NewGuid().ToString("N");

                    m_patient.CitizenId = citizenId;
                    m_patient.HealthCardId = registrationNumber;
                    m_patient.CreateTime = nowDT;

                    m_citizen.CitizenId = citizenId;
                    m_citizen.FullName = fullName;
                    m_citizen.GenderId = genderId;
                    m_citizen.Birthday = birthday;

                    m_newCardChange.DeptId = deptId;
                    m_newCardChange.RecordTime = nowDT;
                    m_newCardChange.Amount = newCardFee;
                    m_newCardChange.Remarks = remark;
                    m_newCardChange.PaymentType = C_PaymentType.CASH;
                    m_newCardChange.IsValid = true;
                    m_newCardChange.BillType = C_BillType.NEW_ACCOUNT;
                }
                else
                {
                    if (m_citizen != null)
                    {
                        citizenId = m_citizen.CitizenId;
                    }
                    else
                    {
                        Alert.ShowDialog(AlertType.Error, "无病人资料");
                    }
                }

                m_registryCharge = new M7_ChargeRecord();
                m_registryCharge.DeptId = deptId;
                m_registryCharge.RecordTime = nowDT;
                m_registryCharge.Amount = registryFee + diagnosticFee;
                m_registryCharge.Remarks = remark;
                m_registryCharge.PaymentType = C_PaymentType.CASH;
                m_registryCharge.IsValid = true;
                m_registryCharge.BillType = C_BillType.REGISTRY_RECORD;

                m_registryRecord = new M7_RegistryRecord();
                m_registryRecord.CitizenId = citizenId;
                m_registryRecord.DeptId = deptId;
                m_registryRecord.DoctorId = doctorId;
                m_registryRecord.OutpatientType = Convert.ToInt32(outpatientTypeId);
                m_registryRecord.RegistryType = Convert.ToInt32(registryTypeId);
                m_registryRecord.InsuranceType = Convert.ToInt32(insuranceTypeId);
                m_registryRecord.OperatorId = Senvironments.CurrentAccount is M7_Employee ? (Senvironments.CurrentAccount as M7_Employee).EmpId : 0;
                m_registryRecord.RecordTime = nowDT;
                m_registryRecord.Amount = totalFee;
                m_registryRecord.VisitNo = visitNo;
                m_registryRecord.Status = C_BillStatus.NEW;
                m_registryRecord.Patient = m_citizen;
            }

            return base.CheckData();
        }

        /// <summary>
        /// Add Data
        /// </summary>
        protected override void AddData()
        {
            int result = -1;
            bool addRegistryRecord = true;
            if (m_currentOperation == OPERATION_NEW_CARD)
            {
                if (m_patient != null && m_citizen != null)
                {
                    result = AddPatient(m_patient, m_citizen);
                    if (result == 1)
                    {
                    }
                    else
                    {
                        addRegistryRecord = false;
                    }
                }
                else
                {
                    Alert.ShowDialog(AlertType.Error, "病人信息对象为NULL");
                    return;
                }
            }

            if (addRegistryRecord && (m_currentOperation == OPERATION_NEW_CARD || m_currentOperation == OPERATION_REGISTRY))
            {
                if (m_registryRecord != null)
                {
                    result = AddRegistryRecord(m_registryRecord);

                    if (result == 1)
                    {
                        if (m_registryCharge != null)
                        {
                            m_registryCharge.BillId = m_registryRecord.RecordId;
                            result = AddChargeRecord(m_registryCharge);

                            if (result == 1)
                            {
                                if (m_currentOperation == OPERATION_NEW_CARD)
                                {
                                    if (m_newCardChange != null)
                                    {
                                        int registryRecordSeed = Agent_SYSS.GetTernarySeed(C_M7_TableName.REGISTRY_RECORD, m_registryRecord.RecordTime.ToString("yyyyMMdd"), C_BillType.NEW_ACCOUNT.ToString());
                                        long registryRecordId = Convert.ToInt64(PrimaryKeyUtil.GetPrimaryKey(C_M7_TableName.REGISTRY_RECORD, m_registryRecord.RecordTime.ToString("yyyyMMdd"), C_BillType.NEW_ACCOUNT, registryRecordSeed));
                                        m_newCardChange.BillId = registryRecordId;
                                        result = AddChargeRecord(m_newCardChange);

                                        if (result == 1)
                                        {
                                        }
                                    }
                                    else
                                    {
                                        Alert.ShowDialog(AlertType.Error, "新开卡费用对象为NULL");
                                        return;
                                    }
                                }
                                else
                                {
                                }
                            }
                        }
                        else
                        {
                            Alert.ShowDialog(AlertType.Error, "挂号费用对象为NULL");
                            return;
                        }
                    }
                }
                else
                {
                    Alert.ShowDialog(AlertType.Error, "挂号信息对象为NULL");
                    return;
                }
                base.AddData();
            }
        }

        /// <summary>
        /// Add Patent
        /// </summary>
        /// <returns></returns>
        private int AddPatient(M7_Patient patient, S7_Citizen citizen)
        {
            int result = -1;
            if (m_currentOperation == OPERATION_NEW_CARD)
            {
                if (patient != null && citizen != null)
                {
                    var __patient = Agent_BIZS.GetPatientByRegistryNo(RegistryNoType.HealthCardId, patient.HealthCardId);
                    if (__patient != null)
                    {
                        Alert.ShowDialog(AlertType.Error, "该卡号{0}已开通并使用中, 请确认该卡是否为新卡", patient.HealthCardId);
                    }
                    else
                    {
                        result = Agent_INFS.AddCitizen(citizen);
                        if (result == 1)
                        {
                            int patientSeed = Agent_SYSS.GetTernarySeed(C_M7_TableName.PATIENT, m_divisionId, patient.CreateTime.ToString("yyyyMMdd"));
                            long patientId = Convert.ToInt64(PrimaryKeyUtil.GetPrimaryKey(C_M7_TableName.PATIENT, m_divisionId, patient.CreateTime.ToString("yyMMdd"), patientSeed));
                            patient.PatientId = patientId;

                            result = Agent_BIZS.AddPatient(patient);
                            if (result == 1)
                            {
                            }
                            else
                            {
                                Alert.ShowDialog(AlertType.Error, "添加个人信息失败");
                            }
                        }
                        else
                        {
                            Alert.ShowDialog(AlertType.Error, "添加个人信息失败");
                        }
                    }
                }
            }
            return result;
        }

        /// <summary>
        /// RegistryRecord
        /// </summary>
        /// <param name="registryRecord"></param>
        /// <returns></returns>
        private int AddRegistryRecord(M7_RegistryRecord registryRecord)
        {
            int result = -1;

            int registryRecordSeed = Agent_SYSS.GetTernarySeed(C_M7_TableName.REGISTRY_RECORD, registryRecord.RecordTime.ToString("yyyyMMdd"), C_BillType.REGISTRY_RECORD.ToString());
            long registryRecordId = Convert.ToInt64(PrimaryKeyUtil.GetPrimaryKey(C_M7_TableName.REGISTRY_RECORD, registryRecord.RecordTime.ToString("yyyyMMdd"), C_BillType.REGISTRY_RECORD, registryRecordSeed));
            registryRecord.RecordId = registryRecordId;

            result = Agent_BIZS.AddRegistryRecord(registryRecord);

            if (result == 1)
            {
            }
            else
            {
                Alert.ShowDialog(AlertType.Error, "添加挂号信息失败");
            }
            
            return result;
        }

        /// <summary>
        /// 添加费用信息
        /// </summary>
        /// <param name="chargeRecord"></param>
        /// <returns></returns>
        private int AddChargeRecord(M7_ChargeRecord chargeRecord)
        {
            int result = -1;

            result = Agent_BIZS.AddChargeRecord(chargeRecord);
            if (result == 1)
            {
            }
            else
            {
                Alert.ShowDialog(AlertType.Error, "添加费用信息失败");
            }

            return result;
        }

        /// <summary>
        /// 初始化添加
        /// </summary>
        protected override void InitializeForCreating()
        { 
            
        }

        /// <summary>
        /// 清除UI上的数据
        /// </summary>
        private void ClearDataOnUI()
        {
            this.txbVisitNo.Text = "";
            this.txbRegistrationNumber.Text = "";
            this.txbFullName.Text = "";
            this.txbAge.Text = "";
            this.txbTotalAmount.Text = "";
            this.txbFatchAmount.Text = "";
            this.txbBillAmount.Text = "";
            this.txbRemark.Text = "";

            dtpBirthday.SelectedDate = null;

            m_citizen = null;

            ShowRegistryFee();
        }

        /// <summary>
        /// 清除UI上的数据
        /// </summary>
        private void ClearDataOnUIForGetPatient()
        {
            this.txbFullName.Text = "";
            this.txbAge.Text = "";
            dtpBirthday.SelectedDate = null;
            m_citizen = null;
        }

        /// <summary>
        /// 清除UI上的数据
        /// </summary>
        private void ClearDateOnUIForRegistrySucess()
        {
            ClearDataOnUI();
        }

        /// <summary>
        /// 挂号
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnRegistry_Click(object sender, RoutedEventArgs e)
        {
            SetCurrentOperationType(OPERATION_REGISTRY);
        }

        /// <summary>
        /// 换号
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnChangeRegistry_Click(object sender, RoutedEventArgs e)
        {
            SetCurrentOperationType(OPERATION_CHANGE_REGISTRY);
        }

        /// <summary>
        /// 预约
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnBespoke_Click(object sender, RoutedEventArgs e)
        {
            SetCurrentOperationType(OPERATION_BESPOKE_REGISTRY);
        }

        /// <summary>
        /// 开卡
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnNewCard_Click(object sender, RoutedEventArgs e)
        {
            SetCurrentOperationType(OPERATION_NEW_CARD);
        }

        /// <summary>
        /// 设置当前操作类型
        /// </summary>
        /// <param name="operationType"></param>
        private void SetCurrentOperationType(int operationType)
        {
            m_currentOperation = operationType;

            ClearDataOnUI();

            if (m_currentOperation == OPERATION_NEW_CARD)
            {
                m_currentCardType = TYPE_MEDICAL_CARD;

                txbFullName.IsReadOnly = false;
                cbbGender.IsEnabled = true;
                dtpBirthday.IsEnabled = true;
                chkNewCard.IsChecked = true;

                txbFullName.Focus();

                ShowVisitNoToUI();
            }
            else
            {
                txbFullName.IsReadOnly = true;
                cbbGender.IsEnabled = false;
                dtpBirthday.IsEnabled = false;
                chkNewCard.IsChecked = false;

                txbFatchAmount.Focus();
            }

            ShowRemarkOnUI();
        }

        /// <summary>
        /// 社保卡
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSocialCard_Click(object sender, RoutedEventArgs e)
        {
            SetCurrentCardType(TYPE_SOCIAL_SECURITY_CARD);
        }

        /// <summary>
        /// 病历号
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnMedicalHistory_Click(object sender, RoutedEventArgs e)
        {
            SetCurrentCardType(TYPE_MEDICAL_HISTORY_CARD);
        }

        /// <summary>
        /// 身份证
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnIdCard_Click(object sender, RoutedEventArgs e)
        {
            SetCurrentCardType(TYPE_IDENTIFICATION_CARD);
        }

        /// <summary>
        /// 医疗卡
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnMedicalCard_Click(object sender, RoutedEventArgs e)
        {
            SetCurrentCardType(TYPE_MEDICAL_CARD);
        }

        /// <summary>
        /// 设置当前操卡类型
        /// </summary>
        /// <param name="operationType"></param>
        private void SetCurrentCardType(int cardType)
        {
            if (m_currentOperation == OPERATION_NEW_CARD)
            {
                if (cardType != TYPE_MEDICAL_CARD)
                {
                    Alert.ShowDialog(AlertType.Error, "新开卡类型只能是医疗卡");
                    return;
                }
            }

            m_currentCardType = cardType;

            ShowRemarkOnUI();
        }

        /// <summary>
        /// Show Record On UI
        /// </summary>
        private void ShowRemarkOnUI()
        {
            string str = "";
            switch (m_currentOperation)
            { 
                case OPERATION_NEW_CARD:
                    str = "新开卡,挂号";
                    break;
                case OPERATION_REGISTRY:
                    str = "挂号";
                    break;
                case OPERATION_CHANGE_REGISTRY:
                    str = "挂号";
                    break;
                case OPERATION_BESPOKE_REGISTRY:
                    str = "预约";
                    break;
            }

            switch (m_currentCardType)
            {
                case TYPE_IDENTIFICATION_CARD:
                    str += ",身份证";
                    break;
                case TYPE_MEDICAL_CARD:
                    str += ",医疗卡";
                    break;
                case TYPE_MEDICAL_HISTORY_CARD:
                    str += ",病历卡";
                    break;
                case TYPE_SOCIAL_SECURITY_CARD:
                    str += ",社保卡";
                    break;
            }

            txbRemark.Text = str;
        }

        /// <summary>
        /// 
        /// </summary>
        private void GetCitizenByRegistrationNumber()
        {
            string registrationNumber = txbRegistrationNumber.Text.Trim();

            if (!string.IsNullOrEmpty(registrationNumber))
            {
                object obj = null;
                if (m_currentOperation != OPERATION_NEW_CARD)
                {
                    if (m_currentCardType == TYPE_MEDICAL_CARD)
                    {
                        ClearDataOnUIForGetPatient();

                        M7_Patient patient = Agent_BIZS.GetPatientByRegistryNo(RegistryNoType.HealthCardId, registrationNumber);
                        if (patient == null)
                        {
                            Alert.ShowDialog(AlertType.Error, "{0}号码无相应记录，请核对后重新输入", registrationNumber);
                        }
                        else
                        {
                            obj = patient;
                        }
                    }
                    else if (m_currentCardType == TYPE_IDENTIFICATION_CARD)
                    {
                        ClearDataOnUIForGetPatient();

                        obj = Agent_INFS.GetCitizenByIdentityId(C_IdentityTypeFlags.ID_CARD, registrationNumber);
                        if (obj == null)
                        {
                            Alert.ShowDialog(AlertType.Error, "{0}号码无相应记录，请核对后重新输入", registrationNumber);
                        }
                    }
                    else if (m_currentCardType == TYPE_MEDICAL_HISTORY_CARD)
                    {

                    }
                    else if (m_currentCardType == TYPE_SOCIAL_SECURITY_CARD)
                    {

                    }
                }

                ShowPationInforToUI(obj as S7_Citizen);
            }
        }

        /// <summary>
        /// 显示病人信息到UI
        /// </summary>
        /// <param name="citizen"></param>
        private void ShowPationInforToUI(S7_Citizen citizen)
        {
            if (citizen != null)
            {
                M7_Patient patient = Agent_BIZS.GetPatientByRegistryNo(RegistryNoType.CitizenId, citizen.CitizenId);
                if(patient != null)
                {
                    m_citizen = citizen;
                    txbFullName.Text = citizen.FullName;
                    cbbGender.SelectedValue = citizen.GenderId;
                    dtpBirthday.SelectedDate = citizen.Birthday;
                    ShowVisitNoToUI();
                }
                else
                {
                    Alert.ShowDialog(AlertType.Error, "此号码未找到医疗卡，请先开卡");
                }
            }
        }
        #endregion

        #region Structure

        /// <summary>
        /// 构造方法
        /// </summary>
        public OutpatientRegistryControl()
        {
            InitializeComponent();
        }
        #endregion

        #region Inner members

        /// <summary>
        /// 挂号
        /// </summary>
        private const int OPERATION_REGISTRY = 0;

        /// <summary>
        /// 行政区编码
        /// </summary>
        private string m_divisionId = "";

        /// <summary>
        /// 换号
        /// </summary>
        private const int OPERATION_CHANGE_REGISTRY = 1;

        /// <summary>
        /// 预约
        /// </summary>
        private const int OPERATION_BESPOKE_REGISTRY = 2;

        /// <summary>
        /// 开卡
        /// </summary>
        private const int OPERATION_NEW_CARD = 3;

        /// <summary>
        /// 社保卡
        /// </summary>
        private const int TYPE_SOCIAL_SECURITY_CARD = 0;

        /// <summary>
        /// 病历号
        /// </summary>
        private const int TYPE_MEDICAL_HISTORY_CARD = 1;

        /// <summary>
        /// 身份证
        /// </summary>
        private const int TYPE_IDENTIFICATION_CARD = 2;

        /// <summary>
        /// 医疗卡
        /// </summary>
        private const int TYPE_MEDICAL_CARD = 3;

        /// <summary>
        /// 当前操作类型
        /// </summary>
        private int m_currentOperation = OPERATION_NEW_CARD;

        /// <summary>
        /// 当前卡类型
        /// </summary>
        private int m_currentCardType = TYPE_MEDICAL_CARD;

        /// <summary>
        /// 门诊类型列表
        /// </summary>
        private List<M7_OutpatientType> m_outpatientTypeList;

        /// <summary>
        /// 挂号类型列表
        /// </summary>
        private List<M7_RegistryType> m_registryTypeList;

        /// <summary>
        /// 医疗类型列表
        /// </summary>
        private List<M7_InsuranceType> m_insuranceTypeTypeList;

        /// <summary>
        /// 性别信息列表
        /// </summary>
        private List<M7_Gender> m_genderList;

        /// <summary>
        /// 一级科室列表
        /// </summary>
        //private List<M7_Department> m_deptList;

        /// <summary>
        /// 二级科室列表
        /// </summary>
        private List<M7_Department> m_subDeptList;

        /// <summary>
        /// 医生列表
        /// </summary>
        private List<M7_Employee> m_empList;

        /// <summary>
        /// 挂号费用列表
        /// </summary>
        private List<M7_RegistryFee> m_registryFeeList;

        /// <summary>
        /// 挂叫信息列表
        /// </summary>
        private List<M7_RegistryRecord> m_registryRecordList;

        /// <summary>
        /// 新开卡费用
        /// </summary>
        private decimal m_newCardFee;

        /// <summary>
        /// 病人信息
        /// </summary>
        private M7_Patient m_patient;

        /// <summary>
        /// 人员信息
        /// </summary>
        private S7_Citizen m_citizen;

        /// <summary>
        /// 挂号记录信息
        /// </summary>
        private M7_RegistryRecord m_registryRecord;

        /// <summary>
        /// 挂号费信息
        /// </summary>
        private M7_ChargeRecord m_registryCharge;

        /// <summary>
        /// 新开卡费信息
        /// </summary>
        private M7_ChargeRecord m_newCardChange;
        #endregion
    }
}
